package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.PropagandaScreeningDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.CaringStaffEnum;
import com.budwk.app.sqfwV2.enums.PropagandaScreeningEnum;
import com.budwk.app.sqfwV2.enums.PropagandaScreeningEnum;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.sqfwV2.service.patrolAndVisit.PatrolAndVisitExcelService;
import com.budwk.app.sqfwV2.service.patrolAndVisit.PatrolAndVisitExcelV2Service;
import com.budwk.app.sqfwV2.service.patrolAndVisit.PatrolAndVisitPdfService;
import com.budwk.app.sqfwV2.service.propagandaScreening.PropagandaScreeningExcelService;
import com.budwk.app.sqfwV2.service.propagandaScreening.PropagandaScreeningPdfService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import java.util.*;
import java.util.stream.Collectors;

@IocBean
@At("/platform/sqfwV2/propagandaScreening")
@ApiDefinition(tag = "宣传排查")
@Slf4j
public class PropagandaScreeningController {
    @Inject
    private PropagandaScreeningPdfService propagandaScreeningPdfService;
    @Inject
    private PropagandaScreeningExcelService propagandaScreeningExcelService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SummarySafetyService summarySafetyService;
    @Inject
    private SysOssService sysOssService;
    @Inject
    private SysUserService sysUserService;


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> getListPage(@Param("pageNo") int pageNo,
                                 @Param("pageSize") int pageSize,
                                 @Param("sort") String sort,
                                 @Param("fillDate") String fillDate,
                                 @Param("type") String type,
                                 @Param("county") String county) {
        SqlExpressionGroup sql =new SqlExpressionGroup();
        SummaryQueryReqVo dto = new SummaryQueryReqVo();
        dto.setPageNo(pageNo);
        dto.setPageSize(pageSize);
        dto.setSort(sort);
        dto.setFillDate(fillDate);
        dto.setFillType(SupportBusinessTypeEnum.PROPAGANDA_SCREENING.getName());
        if(StrUtil.isNotBlank(county)){
            sql.and("county","=",county);
        }
        if(StrUtil.isNotBlank(type)){
            sql.and("param_data ->>'type'","=",type);
        }
        dto.setSqlExpressionGroup(sql);
        return summarySafetyService.listSummaryByPage(dto);
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "生成下载页面")
    @SaCheckLogin
    public Result<?> generateDetailFile(@Param("..") SummaryQueryReqVo reqVo) {
        SqlExpressionGroup sql = new SqlExpressionGroup();
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        // 按照巡查时间查询
        if (StringUtils.isNotEmpty(reqVo.getFillStartDate())) {
            sql.andBetween(Sqfw_formSummary_new::getFillDate, reqVo.getFillStartDate() + " 00:00:00", reqVo.getFillEndDate() + " 23:59:59");
        }
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(Cnd
                .where(Sqfw_formSummary_new::getType,"=",SupportBusinessTypeEnum.PROPAGANDA_SCREENING.getName())
                .and(sysUser.getCommunity().equals("直属")?"county":"community" ,"=",sysUser.getCommunity().equals("直属")?sysUser.getCounty():sysUser.getCommunity())
                .and(sql));

        List<DownFileTypesResVo> downFileTypesResVos = new ArrayList<>();
        PropagandaScreeningEnum[] values = PropagandaScreeningEnum.values();
        for (PropagandaScreeningEnum serviceEnum : values) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setLabel(serviceEnum.getName())
                    .setPreviewImage(List.of(serviceEnum.getPreviewImage().split(",")))
                    .setFileCode(String.valueOf(serviceEnum.getCode()))
                    //.setFilePath(serviceEnum.getBlankTemplate())
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(serviceEnum.getCode())
                    .setFileName(serviceEnum.getFileName());
            if(serviceEnum.getCode()==1){
                resVo.setLabel("宣传记录");
                resVo.setFileType("pdf");
                List<Sqfw_formSummary_new> a= sqfwFormSummaryNews.stream()
                        .filter(s-> JSONObject.parseObject(s.getParamData(), PropagandaScreeningDTO.class).getType().equals(serviceEnum.getName()))
                        .collect(Collectors.toList());
                if(a.size()>0){
                    resVo.setHiveData(true);
                }
            }
            if(serviceEnum.getCode()==2){
                resVo.setLabel("走访排查");
                resVo.setFileType("pdf");
                List<Sqfw_formSummary_new> a= sqfwFormSummaryNews.stream()
                        .filter(s-> JSONObject.parseObject(s.getParamData(), PropagandaScreeningDTO.class).getType().equals(serviceEnum.getName()))
                        .collect(Collectors.toList());
                if(a.size()>0){
                    resVo.setHiveData(true);
                }
            }
            if(serviceEnum.getCode()==3){
                resVo.setFileType("excel");
                List<Sqfw_formSummary_new> a= sqfwFormSummaryNews.stream()
                        .filter(s-> JSONObject.parseObject(s.getParamData(), PropagandaScreeningDTO.class).getType().equals(serviceEnum.getName()))
                        .collect(Collectors.toList());
                if(a.size()>0){
                    resVo.setHiveData(true);
                }
            }
            if(serviceEnum.getCode()==4){
                resVo.setFileType("excel");
                List<Sqfw_formSummary_new> a= sqfwFormSummaryNews.stream()
                        .filter(s-> JSONObject.parseObject(s.getParamData(), PropagandaScreeningDTO.class).getType().equals(serviceEnum.getName()))
                        .collect(Collectors.toList());
                if(a.size()>0){
                    resVo.setHiveData(true);
                }
            }
            downFileTypesResVos.add(resVo);
        }
        return Result.data( NutMap.NEW().addv("list",downFileTypesResVos).addv("totalCount",sqfwFormSummaryNews.size()));
    }



    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载pdf")
    @SaCheckLogin
    public Result<?> downPdfLedgerV2(@Param("..") DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        Integer code=Integer.valueOf(reqVo.getFileCode());
        if (reqVo.isDownTemplate()) {
            String filePath = PropagandaScreeningEnum.getBlankTemplate(code) ;
            String fileName =filePath.substring(filePath.lastIndexOf("/")+1);
            generateExcelUrlVO.setExcelUrl( sysOssService.upload( CommonFormOfficeUtils.getTempPdfFile(filePath),fileName).getUrl());
        }else {
            List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(Cnd.where(
                            Sqfw_formSummary_new::getFillDate, "between", new Object[]{reqVo.getFillStartDate() + " 00:00:00", reqVo.getFillEndDate() + " 23:59:59"})
                    .and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.PROPAGANDA_SCREENING.getName())
                    .and(sysUser.getCommunity().equals("直属") ? "county" : "community", "=", sysUser.getCommunity().equals("直属") ? sysUser.getCounty() : sysUser.getCommunity())
                    .and("param_data->>'type'", "=", PropagandaScreeningEnum.getName(code)));
            if (CollectionUtil.isNotEmpty(formSummaryList)) {
                List<String> summaryIdS = formSummaryList.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
                List<Sqfw_completeflow> completeflow = sqfwCompleteflowService.query(Cnd.where(Sqfw_completeflow::getId, "in", summaryIdS)
                        .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                        .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
                if (CollectionUtil.isNotEmpty(completeflow)) {
                    List<String> pdfPathList = completeflow.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
                    String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, PropagandaScreeningEnum.getFileName(code));
                    generateExcelUrlVO.setExcelUrl(url);
                }
            }
        }
        return Result.data( generateExcelUrlVOS);
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成excel")
    @SaCheckLogin
    public Result<?> downExcelLedgerV2(@Param("..") DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        Integer code=Integer.valueOf(reqVo.getFileCode());
        if (reqVo.isDownTemplate()) {
            String filePath = PropagandaScreeningEnum.getBlankTemplate(code);
            String fileName =filePath.substring(filePath.lastIndexOf("/")+1);
            generateExcelUrlVO.setExcelUrl( sysOssService.upload( CommonFormOfficeUtils.getTempPdfFile(filePath),fileName).getUrl());
        } else {
            CompleteFlowExcelParamForController paramForController = new CompleteFlowExcelParamForController();
            List<ExcelCreateConfig> excelCreateConfigList = new ArrayList<>();
            ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(String.valueOf(code));
            excelCreateConfig.setParam(NutMap.NEW()
                    .addv("fillStartDate", reqVo.getFillStartDate() + " 00:00:00")
                    .addv("fillEndDate", reqVo.getFillEndDate() + " 23:59:59"));

            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            List<ResultOfExcelGenerator> excel = propagandaScreeningExcelService.createExcel(paramForController);

            if (CollectionUtil.isNotEmpty(excel)) {
                generateExcelUrlVO.setExcelUrl(excel.get(0).getExcelUrl());
            }
        }
        return Result.data( generateExcelUrlVOS);
    }
}
